package com.toe.common.utils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.dysmsapi.model.v20170525.*;
import com.google.gson.Gson;
import com.toe.common.config.AliConfig;

import java.util.Random;

public class AliYunSmsUtils {

    /**
     * 发送验证码的方法
     * @param phone 手机号
     * @return 发送成功返回验证码, 发送失败返回字符串no, 不是手机号返回np
     */
    public static String sendCodeSms(String phone) {
        if (!isPhone(phone)) {
            return "np";
        }

        /** use STS Token
         DefaultProfile profile = DefaultProfile.getProfile(
         "<your-region-id>",           // The region ID
         "<your-access-key-id>",       // The AccessKey ID of the RAM account
         "<your-access-key-secret>",   // The AccessKey Secret of the RAM account
         "<your-sts-token>");          // STS Token
         **/
        DefaultProfile profile = DefaultProfile.getProfile(
                AliConfig.REGION_ID,
                AliConfig.ACCESS_KEY_ID,
                AliConfig.ACCESS_KEY_SECRET
        );

        IAcsClient client = new DefaultAcsClient(profile);

        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(phone);//接收短信的手机号码
        request.setSignName("阿里云短信测试");//短信签名名称
        request.setTemplateCode("SMS_154950909");//短信模板CODE

        Random random = new Random();
        int code = random.nextInt(8999) + 1000;
        request.setTemplateParam("{\"code\":\""+ code +"\"}");//短信模板变量对应的实际值

        System.out.println("发送的手机号: " + phone);
        System.out.println("验证码为: " + code);
        System.out.println("REGION_ID: "+AliConfig.REGION_ID);
//        System.out.println("签名: "+AliConfig.SIGN_NAME);

        SendSmsResponse response = null;
//        try {
//            response = client.getAcsResponse(request);
//            System.out.println(new Gson().toJson(response));
//        } catch (ServerException e) {
//            e.printStackTrace();
//            return "no";
//        } catch (ClientException e) {
//            System.out.println("ErrCode:" + e.getErrCode());
//            System.out.println("ErrMsg:" + e.getErrMsg());
//            System.out.println("RequestId:" + e.getRequestId());
//            return "no";
//        }
//
//        if ("OK".equals(response.getCode())) {
//            System.out.println("发送成功了");
//            return code+"";
//        }
//
//        return "no";
        //测试需要,后期再改回来
        return code+"";
    }

    /**
     * 验证是否为 手机号(手机)的方法
     * @param phone
     * @return
     */
    private static boolean isPhone(String phone){
        if(phone.matches("^[1][3,4,5,7,8,9][0-9]{9}$")){
            return true;
        }else{
            return false;
        }
    }

}
